package com.onegroup.common;

import com.onegroup.common.enums.ResponseStatusEnum;
import com.onegroup.pojo.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author: 曾雪斌
 * @Description: 数据返回前端之前进行增强处理
 * @History:
 */
@RestControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 方法的返回值类型进行判断是否需要进行增强处理
     * @param returnType 返回值类型
     * @return 返回false不需要增强，true表示需要增强处理
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 返回类型不正确则支持增强处理
        return !returnType.getGenericParameterType().equals(ResponseResult.class);
    }

    /**
     * 该方法是对返回值的增强处理
     * @param body controller中return的数据
     * @return 结果集
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        ResponseResult<Object> result = new ResponseResult<>(ResponseStatusEnum.SUCCESS);
        if(ObjectUtils.isEmpty(body)) {
            return result;
        }
        if (body instanceof ResponseResult) {
            return body;
        }
        result.setData(body);
        return result;
    }

}
